<template>
    <el-container class="chat-session-list-container">
        <el-header height="40" style="padding: 0px;">
            <el-input v-model="searchQuery" placeholder="搜索会话" :suffix-icon="searchQuery ? '' : 'Search'"
                @clear="searchQuery = ''" clearable></el-input>
        </el-header>

        <el-scrollbar class="chat-session-list">
            <el-collapse v-model="collapses" expand-icon-position="left">
                <el-collapse-item title="我的收藏" name="1">
                    <ChatSessionListItem v-for="session in collectSessionList" :key="session.id" :session="session"
                        :active="currentSession && currentSession.id === session.id" @click="changeSession"
                        @afterUpdateSession="afterUpdateSession" @afterDeleteSession="afterDeleteSession" />
                </el-collapse-item>
                <el-collapse-item title="置顶会话" name="2">
                    <ChatSessionListItem v-for="session in topSessionList" :key="session.id" :session="session"
                        :active="currentSession && currentSession.id === session.id" @click="changeSession"
                        @afterUpdateSession="afterUpdateSession" @afterDeleteSession="afterDeleteSession" />
                </el-collapse-item>
                <el-collapse-item title="最近会话" name="3">
                    <ChatSessionListItem v-for="session in simpleSessionList" :key="session.id" :session="session"
                        :active="currentSession && currentSession.id === session.id" @click="changeSession"
                        @afterUpdateSession="afterUpdateSession" @afterDeleteSession="afterDeleteSession" />
                </el-collapse-item>

            </el-collapse>


        </el-scrollbar>
        <div style="text-align: center; margin-top: 10px;">
            <el-button type="primary" size="small" @click="sessionListModalVisible = true">管理会话记录</el-button>
        </div>
        <el-footer height="45">
            <ChatSessionListModal v-model:visible="sessionListModalVisible" :application-id="applicationId"
                @update:visible="fetchChatSessionList" />
        </el-footer>
    </el-container>
</template>

<script>

import { useUserInfoStore } from '@/stores/userInfo';
import ChatSessionListModal from './ChatSessionListModal.vue';
import ChatSessionListItem from './ChatSessionListItem.vue';
export default {
    setup() {
        const userInfoStore = useUserInfoStore();
        const { username } = userInfoStore.basicInfo;
        return {
            username
        };
    },
    components: {
        ChatSessionListModal,
        ChatSessionListItem,
    },
    props: {
        applicationId: {
            type: [String, Number],
            required: true
        },
        sessionId: {
            type: [String, Number],
            required: false,
        }
    },
    emits: ['changeSession'],
    data() {
        return {
            sessionList: [], // 会话列表,
            collectSessionList: [], // 收藏会话列表
            topSessionList: [],// 置顶会话列表
            simpleSessionList: [], // 普通会话列表
            currentSession: null,
            searchQuery: '',
            sessionListModalVisible: false,
            collapses: ['1', '2', '3'], // 默认展开所有分类
        };
    },
    watch: {
        sessionId(val) {
            this.handleCurrentSession();
        },
        searchQuery(val) {
            // 可以在这里添加搜索逻辑，目前只是简单的过滤
            const query = val.toLowerCase();
            const sessionList = this.sessionList.filter(s => s.title.toLowerCase().includes(query));
            // 重新分类
            this.collectSessionList = sessionList.filter(s => s.collectFlag);
            this.topSessionList = sessionList.filter(s => s.topFlag);
            this.simpleSessionList = sessionList.filter(s => !s.collectFlag && !s.topFlag);
        }
    },
    mounted() {
        this.fetchApplication();
        this.fetchChatSessionList();
    },
    methods: {
        fetchApplication() {
            // Fetch the application details from the API or store
        },
        changeSession(session) {
            console.log('Changing session to:', session);
            this.currentSession = session;
            this.$emit('changeSession', session);
        },
        fetchChatSessionList() {
            this.$api.ai.getChatSessionList(this.applicationId).then(response => {
                const sessionList = response.data;
                this.sessionList = sessionList;
                this.collectSessionList = sessionList.filter(s => s.collectFlag);
                this.topSessionList = sessionList.filter(s => !s.collectFlag && s.topFlag);
                this.simpleSessionList = sessionList.filter(s => !s.collectFlag && !s.topFlag);
                this.handleCurrentSession();
            });
        },
        handleCurrentSession() {
            const allSessions = [...this.simpleSessionList, ...this.collectSessionList, ...this.topSessionList];

            if (this.sessionId) {
                this.currentSession = allSessions.find(s => s.id + '' === this.sessionId + '') || null;
                // 如果传入的 sessionId 不存在于会话列表中，则不做任何处理
                if (!this.currentSession) {
                    // 默认选择第一个会话
                    if (allSessions.length > 0) {
                        this.changeSession(allSessions[0]);
                    } else {
                        // 如果没有会话，则创建一个新会话
                        this.createNewSession();
                    }
                }
            } else {
                // 如果没有传入 sessionId，则默认选择第一个会话
                if (allSessions.length > 0) {
                    this.changeSession(allSessions[0]);
                } else {
                    // 如果没有会话，则创建一个新会话
                    this.createNewSession();
                }
            }
        },
        createNewSession() {
            this.currentSession = {
                id: -1,
                title: '新建会话',
                isTop: false,
            }
            this.$emit('changeSession', this.currentSession);
        },
        afterUpdateSession(session) {
            this.fetchChatSessionList();
        },
        afterDeleteSession(sessionId) {
            this.fetchChatSessionList();
        }
    }
}
</script>

<style lang="scss" scoped>
.chat-session-list-container {
    padding: 12px 16px;
    width: 300px;
    height: 100%;

    .chat-session-list {
        font-size: 14px;
    }

    :deep(.el-collapse-item__title) {
        color: #A8ABB2;
    }
}
</style>
